package com.zz.nondatain.network;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit客户端单例类
 */
public class RetrofitClient {
    
    private static final String DEFAULT_BASE_URL = "https://139.155.134.12:8201"; // 默认API基础URL
    private static final String BAIDU_AI_BASE_URL = "https://aip.baidubce.com/"; // 百度AI平台基础URL
    private static final long TIMEOUT = 30; // 超时时间（秒）
    
    private static RetrofitClient defaultInstance;
    private static RetrofitClient baiduInstance;
    
    private final Retrofit retrofit;
    
    private RetrofitClient(String baseUrl) {
        // 创建日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        
        // 创建OkHttpClient，处理SSL证书问题
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor);
        
        // 如果是开发环境，可以添加信任所有证书的配置
        if (baseUrl.equals(BAIDU_AI_BASE_URL) || baseUrl.equals(DEFAULT_BASE_URL)) {
            try {
                // 创建信任所有证书的TrustManager
                final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
                };
                
                // 创建SSL上下文
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                
                // 创建SSL Socket工厂
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                
                // 配置OkHttpClient使用自定义SSL配置
                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier((hostname, session) -> true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        OkHttpClient okHttpClient = builder.build();
        
        // 创建Retrofit实例
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }
    
    /**
     * 获取默认RetrofitClient单例
     */
    public static synchronized RetrofitClient getInstance() {
        if (defaultInstance == null) {
            defaultInstance = new RetrofitClient(DEFAULT_BASE_URL);
        }
        return defaultInstance;
    }
    
    /**
     * 获取百度AI平台RetrofitClient单例
     */
    public static synchronized RetrofitClient getBaiduInstance() {
        if (baiduInstance == null) {
            baiduInstance = new RetrofitClient(BAIDU_AI_BASE_URL);
        }
        return baiduInstance;
    }
    
    /**
     * 创建自定义baseUrl的RetrofitClient实例
     */
    public static RetrofitClient createInstance(String baseUrl) {
        return new RetrofitClient(baseUrl);
    }
    
    /**
     * 获取API服务接口
     */
    public ApiService getApiService() {
        return retrofit.create(ApiService.class);
    }
} 